<?php
namespace app\api\service;

use think\facade\Request;
class Wechat{
	public function getAccessToken(){
    $wxAppID =  config('wx.app_id');
    $wxAppSecret = config('wx.app_secret');
    $wxAccessTokenUrl = sprintf(
        config('wx.access_token_url'), $wxAppID, $wxAppSecret);
        $result = curl_get($wxAccessTokenUrl);
        $wxAccessToken = json_decode($result,true);
        $result = $wxAccessToken['access_token'];
       return $result;
}

 public function sends($data){
    $uid = $data['uid'];
    $order_id = $data['order_id'];
    $order = db('order')->field('out_trade_no,order_total_price,total_count')->where('id',$order_id)->find();
    $o_goods = db('order_goods')->field('goods_title')->where('order_id',$order_id)->find();
    $order['goods_title'] = $o_goods['goods_title'];


 	$templateId = config('wx.template_id');
 	//openid根据用户uid去找
    $user = db('user')->field('openid')->where('id',$uid)->find();
 	$openId = $user['openid'];
 
 	$this->sendMessage($openId,$templateId,$order);
 }


public function sendMessage($openId,$templateId,$order)
    {
        //获取access_token
        // $accessToken = new AccessToken();
        $access_token = $this ->getAccessToken();
       
        //要发送给微信接口的数据
        $send_data = [
            //用户openId
            "touser" => $openId,
            //模板id
            "template_id" => $templateId,
            //指定发送到开发版
            "miniprogram_state"=>"developer",
            // //点击跳转到小程序的页面
            // "page"=>'home',
            "data"=>[
                "character_string1" => [
                    "value"=> $order['out_trade_no']
                ],
               
                "thing4" => [
                    "value"=> $order['goods_title']
                ],
                "time8" => [
                    "value"=> date('Y-m-d H:i:s',time())
                ],
                "number5" => [

                    "value"=> $order['total_count']
                ],
                 "amount7" => [
                    "value"=> $order['order_total_price']
                ],
                 
            ],
        ];
        //将路径中占位符%s替换为$access_token值
        $urls = sprintf(config('wx.sendTemplateMessage_url'), $access_token);
        // dump($urls);
        $ret = curl_post($urls, $send_data);
      
        if($ret){
            return_json(200,'成功',$order);
        }else{
            return_json(400,'失败',false);
        }
        
    }
}
?>